const remoteTableConfig = function (headers = {},
                                    where = {conditions: [], sorts: [], data: {}},
                                    page = {}) {
    // --------------
    this.headers = headers;
    this.where = where;
    this.page = page;
};

// 设置remoteTableConfig属性
remoteTableConfig.prototype.setProperty = function (k, v) {
    this[k] = v;
};

// 设置请求头
remoteTableConfig.prototype.setHeader = function (key, value) {
    this.headers[key] = value
};

// 设置查询条件
remoteTableConfig.prototype.setCondition = function (key, value) {
    this.where.Condition[key] = value
};

remoteTableConfig.prototype.setConditions = function (conditions) {
    this.where.Condition = conditions
};

// 设置排序
remoteTableConfig.prototype.setSort = function (obj) {
    this.where.Sort = obj
};

remoteTableConfig.prototype.setSortValue = function (key, value) {
    this.where.Sort[key] = value
};

// 设置分页
remoteTableConfig.prototype.setPage = function (key, value) {
    this.page[key] = value;
};

layui.define([ 'table', 'layer', 'form', 'jquery', 'helper', 'request', 'user', 'setter' ], function (exports) {

    var $ = layui.jquery
        , helper = layui.helper
        , user = layui.user
        , table = layui.table
        , events = layui.setter.events
        , layer = layui.layer
        , context = layui.setter.context;

    var grid = {}

    grid.tableHeight = function (value = 210) {
      var h = $("#table-search").height() ?? 0
      return $(window).height() - h - value;
    }

    grid.toTableData = function(res) {
        if (res && res.code !== 200) {
            layer.msg(res.message || '请求失败', {icon: 2});
            return { "code": 0,  "msg": res.message,  "count": 0, "data": [] }
        }
        return { "code": 0, "msg": res.message, "count": res.count, "data": res.data };
    }


    grid.init = function (tableId, options) {

        options = $.extend({
            "height": this.tableHeight(),
            "elem": "#" + tableId,
            "limit": 20,
            "limits": [10, 20, 50, 100],
            "cols": [],
            contentType: 'application/json',
            "method": "post",
            "request": {"pageName": "page", "limitName": "pageSize"},
            parseData: this.toTableData,
            "toolbar": "#toolBar",
            "page": {"hash": "fenye"},
            "autoSort": false,
            "defaultToolbar": ["filter"]
        }, options || {});


        var cfg = new remoteTableConfig()
        cfg.setHeader("Token", user.token())

        options = $.extend(cfg, options);

        if (helper.hasKey(options, 'page')) {
            helper.hasKeyFnt(options['page'], 'hash', function (page, hash) {
                options = $.extend(options, {page: {
                        'curr': location.hash.replace('#!' + page[hash] + '=', ''),
                        'hash': page[hash]
                }});
            });
        }

        var render = table.render(options);

        table.on('toolbar(' + tableId + '-filter)', function (obj) {
            var dataMap = {};
            var data = $(this).context.dataset;
            for (const key in data) {
                dataMap[key] = data[key];
            }
            events[obj.event] && events[obj.event]({
                type: 'toolbar',
                'tableIns': render,
                'config': $.extend(obj.config[obj.event + "-event"] || {}, dataMap),
                that: $(this)
            });
        })

        table.on('tool(' + tableId + '-filter)', function (obj) {
            var dataMap = {};
            var data = $(this).context.dataset;
            for (const key in data) {
                dataMap[key] = data[key];
            }
            events[obj.event] && events[obj.event]({
                type: 'tool',
                'tableIns': render,
                data: obj.data,
                'config': $.extend(obj.config[obj.event + "-event"] || {}, dataMap),
                that: $(this)
            });
        })

        context.setTable(tableId, render);
    }

    grid.search = function (tableId, conditions) {
        context.getTable(tableId).reload({
            where: {
                conditions: conditions ?? []
            },
            page: {
                page: 1
            }
        });
    }

    exports("grid", grid)
})
